<template>
  <div>
    <!-- 查询 -->
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="部门名称">
        <el-input v-model="formInline.deptName" placeholder="请输入部门名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="formInline.status" placeholder="部门状态">
          <el-option label="正常" value="0"></el-option>
          <el-option label="停用" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit" icon="el-icon-search">搜索</el-button>
        <el-button @click="reset" icon="el-icon-refresh">重置</el-button>
      </el-form-item>
    </el-form>


    <!-- 新增 -->
    <el-col :span="1"><el-button type="primary" icon="el-icon-plus" @click="save">新增</el-button></el-col>


    <!-- 树形结构展示列表 -->
    <el-table
        :data="tableData"
        style="width: 100%;margin-bottom: 20px;"
        row-key="id"
        border
        default-expand-all
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column
          prop="deptName"
          label="部门名称">
      </el-table-column>
      <el-table-column
          prop="orderNum"
          label="排序">
      </el-table-column>
      <el-table-column
          prop="status"
          label="状态">
        <template v-slot="scope">
          {{scope.row.status==='0'?'正常':'停用'}}
        </template>
      </el-table-column>
      <el-table-column
          prop="createTime"
          label="创建时间">
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="text"
                   icon="el-icon-edit"
                   @click="handleEdit(scope.row)">修改</el-button>
          <el-button type="text"
                     icon="el-icon-plus"
                     @click="save(scope.row)" v-if="username == 'admin'">新增</el-button>
          <el-button type="text"
                   icon="el-icon-delete"
                   @click="handleDelete(scope.row)" v-if="scope.row.orderNum !== 0">删除</el-button>
        </template>
      </el-table-column>
    </el-table>



    <!-- 对话框(添加或者修改) -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" width="600px">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="80px" class="demo-ruleForm">
        <el-row>
          <el-col :span="24" v-if="ruleForm.parentId !== 0">
            <el-form-item label="上级部门">
              <el-select v-model="parentName"
                         ref="select"
                         filterable
                         placeholder="选择上级部门"
                         clearable>
                <!-- 后端获取下拉框数据并进行格式化 -->
                <el-option v-for="item in formatData(options)"
                           :key="item.value" :label="item.label" :value="item.value"
                           style="display: none;"/>
                <!-- 获取后端树形结构数据并选中赋值 -->
                <el-tree :data="options"
                         @node-click="handleNodeClick"
                         check-on-click-node></el-tree>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门名称" prop="deptName">
              <el-input v-model="ruleForm.deptName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="ruleForm.orderNum" controls-position="right" :min="0"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="leader">
              <el-input v-model="ruleForm.leader"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="ruleForm.phone"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="ruleForm.email"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门状态">
              <el-radio-group v-model="ruleForm.status">
                <el-radio label="0">正常</el-radio>
                <el-radio label="1">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "DeptView",
  data: function () {
    // 自定义校验deptName(当数据库存在该名称,提示已存在,禁止选择)
    let checkName = (rule, value, callback) => {
      if(this.title == "添加部门"){
        this.axios.post("/dept/dept/getName?deptName=" + value).then(res => {
          if (res.data.code === 200) {
            callback();
          } else {
            callback(res.data.message);
          }
        })
      }else{
        callback();
      }
    }
    return {
      options: [],
      parentName: '',
      username: '',
      formInline: {
        deptName: '',
        status: ''
      },
      tableData: [],
      dialogFormVisible: false,
      title: '',
      ruleForm: {
        deptId: "",
      },
      rules: {
        deptName: [
          {required: true, message: '部门名称不能为空', trigger: 'blur'},
          {validator: checkName, trigger: 'blur'}
        ],
        orderNum: [
          {required: true, message: '显示顺序不能为空', trigger: 'blur'},
        ],
        leader: [
          {required: true, message: '负责人不能为空', trigger: 'blur'},
        ],
        phone: [
          {required: true, pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的联系电话', trigger: 'blur'},
        ],
        email: [
          {required: true, type: "email", message: '邮箱不能为空', trigger: ["blur", "change"]},
        ],
      },
    }
  },
  /** 钩子函数:创建视图就执行 */
  created(){
    sessionStorage.setItem("username","admin");
    this.load();
  },
  methods:{
    /** 获取下拉框中的列表数据 */
    selectObj(){
      this.axios.post("/dept/dept/parentName").then(res=>{
        console.log(res.data.data);
        this.options = res.data.data;
      })
    },
    /** 选中下拉数据并赋值 */
    handleNodeClick(node) {
      console.log("选中的父部门名称:" + node.label);
      this.parentName = node.label;
      // 点击后关闭下拉框，因为点击树形控件后select不会自动折叠
      this.$refs.select.blur();
    },
    /** 格式化后端获取的数据 四级菜单展示在页面 */
    formatData(data){
      let options = [];
      data.forEach((item,key) => {
        options.push({label:item.label,value:item.id});
        if(item.children){
          item.children.forEach((items,keys) => {
            options.push({label:items.label,value:items.id});
            if(items.children){
              items.children.forEach((itemss,keyss) => {
                options.push({label:itemss.label,value:itemss.id});
                if(itemss.children){
                  itemss.children.forEach((itemsss,keysss) => {
                    options.push({label:itemsss.label,value:itemsss.id});
                  });
                }
              });
            }
          });
        }
      });
      return options;
    },
    /** 树形结构列表 */
    load(){
        this.username = sessionStorage.getItem("username");
        this.axios.post("/dept/dept/list",this.formInline).then(res=>{
          console.log(res.data.data);
          this.tableData = res.data.data;
        })
    },
    /** 查询 */
    onSubmit(){
        this.load();
    },
    /** 重置查询条件 */
    reset(){
      this.formInline = {};
      this.load();
    },
    /** 表单重置 */
    res(){
      this.parentName = "";
      this.ruleForm = {
        status: "0",
        phone: '18823968337',
        email: '1309661044@qq.com'
      }
      this.dialogFormVisible = false;
    },
    /** 添加 */
    save(row){
      this.res();
      this.selectObj();
      this.title = "添加部门";
      console.log("当前对象deptId:" + row.id);
      if(row.id !== undefined || row.id != null){
        this.axios.post("/dept/dept/getOne?deptId=" + row.id).then(res=>{
          console.log("上级部门名称:" + res.data.data.deptName);
          this.parentName = res.data.data.deptName;
          this.axios.post("/dept/dept/orderNum?deptId=" + res.data.data.deptId).then(res=>{
            console.log("新的排序:" + res.data.data);
            this.ruleForm.orderNum = res.data.data;
          })
        })
      }
      this.dialogFormVisible = true;
    },
    /** 修改 */
    handleEdit(row){
      this.selectObj();
      this.title = "修改部门";
      console.log("当前对象deptId:" + row.id)
      this.axios.post("/dept/dept/getOne?deptId=" + row.id).then(res=>{
        this.ruleForm = res.data.data;
        if(res.data.data.parentId != 0){
          this.axios.post("/dept/dept/getParentId?parentId=" + res.data.data.parentId).then(res=>{
            this.parentName = res.data.data.deptName;
          });
        }
      })
      this.dialogFormVisible = true;
    },
    /** 对话框表单校验重置 */
    resetForm: function () {
      this.$refs["ruleForm"].clearValidate();
      this.dialogFormVisible = false;
    },
    /** 对话框提交(修改或添加) */
    submitForm: function () {
      this.axios.post("/dept/dept/selectName?parentName=" + this.parentName).then(res=>{
        console.log("父部门deptIId:" + res.data.data.deptId);
        this.ruleForm.parentId = res.data.data.deptId;
        this.$refs["ruleForm"].validate(valid => {
          if (valid) {
            console.log("当前对象deptId:" + this.ruleForm.deptId);
            this.ruleForm.parentName = this.parentName;
              this.axios.post("/dept/dept/saveOrUpdate",this.ruleForm).then(res=>{
                if(res.data.code == 200){
                  this.$message.success(res.data.message);
                  this.dialogFormVisible = false;
                  this.load();
                }else{
                  this.$message.error(res.data.message);
                }
              })
            }
        });
      })
    },
    /** 删除 */
    handleDelete(row){
        this.$confirm( '是否确认删除名称为"' + row.deptName + '"的部门',"警告",{
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(()=>{
          this.axios.post("/dept/dept/del?deptId=" + row.id).then(res=>{
            if(res.data.code == 200){
              this.$message.success("删除成功");
              this.load();
            }else{
              this.$message.error(res.data.message);
            }
          })
        }).catch(()=>{
          this.$message.info("已取消删除");
        })
    }
  }
}
</script>

<style scoped>
.el-dropdown {
  vertical-align: top;
}
.el-dropdown + .el-dropdown {
  margin-left: 15px;
}
.el-icon-arrow-down {
  font-size: 12px;
}
</style>